﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace ViewComponents.Behaviours
{
    public static class OnEnterKeyBehaviour
    {
        public static ICommand GetOnEnterKeyCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(OnEnterKeyCommandProperty);
        }

        public static void SetOnEnterKeyCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(OnEnterKeyCommandProperty, value);
        }

        public static readonly DependencyProperty OnEnterKeyCommandProperty =
                DependencyProperty.RegisterAttached("OnEnterKeyCommand", typeof(ICommand), typeof(OnEnterKeyBehaviour),
                 new UIPropertyMetadata(null, OnEnterKeyCommandPropertyChanged));


        static void OnEnterKeyCommandPropertyChanged(DependencyObject obj,
                DependencyPropertyChangedEventArgs e)
        {
            ((UIElement)obj).KeyDown += new KeyEventHandler(OnEnterKeyBehaviour_KeyDown);
        }

        static void OnEnterKeyBehaviour_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UIElement element = ((UIElement)sender);
                ICommand command = GetOnEnterKeyCommand(element);
                if (command.CanExecute(null))
                    command.Execute(null);
            }
        }
    }
}
